package com.escool.controller;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.escool.model.TbMateria;
import com.escool.service.MateriaService;

@Controller
public class MateriaController {
	
	@Autowired
	MateriaService materiaService;
	
	@RequestMapping("showMateria")
	public String listMateria(Map<String, Object> map){
		map.put("materia", new TbMateria());
		map.put("materiaList", materiaService.listMateria());
		return "/materia";
	}
	
	@RequestMapping(value="addMateria",method= RequestMethod.POST)
	public String addMateria(@ModelAttribute("materia") @Valid TbMateria materia, BindingResult result){
		if(!result.hasErrors()){
			materiaService.addMateria(materia);
			return "redirect:/showMateria";
		}
		return "";
	}
	
	@RequestMapping(value="editMateria",method= RequestMethod.POST)
	public String editMateria(@ModelAttribute("materia") @Valid TbMateria materia, BindingResult result){
		if(!result.hasErrors()){
			materiaService.updateMateria(materia);
			return "redirect:/showMateria";
		}
		return "";
	}
	
	@RequestMapping(value="deleteMateria",method= RequestMethod.POST)
	public String deleteMateria(@ModelAttribute("materia") @Valid TbMateria materia, BindingResult result){
		if(!result.hasErrors()){
			materiaService.deleteMateria(materia.getIdMateria());
			return "redirect:/showMateria";
		}
		return "";
	}

}
